package org.jaaksi.test.encode;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.client.HttpClient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class MyActivity extends Activity
{
	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ImageView imageView = (ImageView) findViewById(R.id.imageView);
		// url = http://www.baidu.com/tieba?id=魔兽&世界吧&key=英雄联盟
		String url = "http%3a%2f%2fwww.baidu.com%2ftieba%3fid%3d%e9%ad%94%e5%85%bd%26%e4%b8%96%e7%95%8c%e5%90%a7"
		        + "%26key%3d%e8%8b%b1%e9%9b%84%e8%81%94%e7%9b%9f";
		try
		{
			String decode = URLDecoder.decode(url, "utf-8");
			Log.i("fcy",
			        "----------------- encode:" + url + "\ndecode:" + decode);
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}

		Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
		        R.drawable.header);
		// TODO 将图片转换成 字节数组，然后经过 Base64编码成字符串，上传给服务器
		String str = Base64.encodeToString(bitmap2Bytes(bitmap),
		        Base64.DEFAULT);
		byte[] bytes = Base64.decode(str, Base64.DEFAULT);
		bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		imageView.setImageBitmap(bitmap);
	}

	public byte[] bitmap2Bytes(Bitmap bm)
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		return baos.toByteArray();
	}
}
